package com.bw.filter;

import com.bw.utils.JwtTokenUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wlz
 */
@Component
public class MyGlobalFilter  implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //请求对象
        ServerHttpRequest request = exchange.getRequest();
        //获取uri
        URI uri =request.getURI();
        //获取请求的路径
        String path = uri.getPath();

        if(path.contains("login")){
            return chain.filter(exchange);
        }

        //获取token
        String token = request.getHeaders().getFirst("authorization");
        //获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //判断token为null
        if(StringUtils.isBlank(token)){
            return  responseAuth(response);
        }

        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        try {
            boolean flag = jwtTokenUtil.validateToken(token);
            if (flag) {
                return chain.filter(exchange);
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }


        return responseAuth(response);

    }


    private Mono<Void> responseAuth(ServerHttpResponse response) {
        //定义返回的数据
        Map<String,Object> responseData = new HashMap<>();
        responseData.put("code", 401);
        responseData.put("message", "非法请求");
        responseData.put("cause", "Token is null");

        ObjectMapper objectMapper = new ObjectMapper();
        try {
            String json = objectMapper.writeValueAsString(responseData);
            //数据缓冲
            DataBuffer dataBuffer = response.bufferFactory().wrap(json.getBytes());
            //设置响应类型
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            //写出
            return response.writeWith(Mono.just(dataBuffer));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
